<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :permission="permissionList"
      :search.sync="search"
      ref="crud"
      :row-class-name="tableRowClassName"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @on-load="onLoad"
      @row-dblclick="rowDblclick"
    >
      <template slot="objectSnSearch">
        <el-input ref="productSequenceNumber" placeholder="请输入产品序列号" @keyup.enter.native="submitSequenceNumber" v-model="search.objectSn" clearable> </el-input>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <!-- <template slot-scope="{ row }" slot="menu">
        <el-button type="text" size="small" icon="el-icon-delete" plain style="border: 0; background-color: transparent !important" @click="handleDelete(row)">删 除 </el-button>
      </template> -->
      <template slot="menu" slot-scope="{ row }">
        <el-button @click="detailEvent(row)" type="text" size="small" plain style="border: 0; background-color: transparent !important" class="el-icon-view"> 详情 </el-button>
      </template>
      <!-- <template slot-scope="{ row }" slot="scrapType">
        <el-tag v-if="row.scrapType == 'P-SCRAP'">产品报废</el-tag>
        <el-tag v-else-if="row.scrapType == 'M-SCRAP'">维修报废</el-tag>
      </template> -->
      <span slot="footer" class="footer">
        <el-button size="small" type="primary" v-if="permission.scopeConfim_confirm" :disabled="ids.length > 0 ? false : true" @click="onScopeSure">确认报废</el-button>
        <!-- <el-button size="small" @click="selectionClear">清 空</el-button> -->
      </span>
    </avue-crud>
    <el-dialog append-to-body :title="dialogTitle" :visible.sync="printLabelModal" @close="printLabelModal = false">
      <avue-form :key="timer" ref="printLabelForm" v-model="scopeDetail" v-if="printLabelModal" :option="scopeOption"> </avue-form>
      <avue-crud :key="timer" ref="crud2" v-if="sequenceNumberTable" :option="sequenceOption" :data="sequenceData"> </avue-crud>
      <span slot="footer" class="dialog-footer">
        <!-- <el-button v-if="scopeDetail.scrapType == 'M-SCRAP'" size="small" type="primary" @click="onRejection">残忍拒收</el-button> -->
        <el-button size="small" @click="printLabelModal = false">关 闭</el-button>
      </span>
    </el-dialog>
  </basic-container>
</template>

<script>
import { submit, add } from '@/api/repair/failurerecord';
// import { getList, getDetail } from '@/api/repair/repairout';
import { confirmScrap, refuseScrap, getProductSequenceInfo, getList, getDetail } from '@/api/repair/scope-confim';

import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  name: 'RepairScopeConfim',
  components: {
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'SCOPE_CONFIM',
      form: {},
      query: {},
      timer: null,
      loading: false,
      scopeProdList: [],
      sequenceNumberTable: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search: {},
      sequenceData: [],
      sequenceOption: {
        viewBtn: false,
        selection: false,
        searchBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        emptyBtn: false,
        menu: false,
        column: [
          {
            label: '序列号',
            prop: 'sequenceNumber'
          }
        ]
      },
      option: {
        height: 'calc(100vh - 435px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        selection: false,
        searchBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        emptyBtn: false,
        // searchBtnText: '选择',
        menuWidth: 200, //弹框内字段宽度属性
        searchLabelWidth: '100',
        columnBtn: false,
        column: [
          {
            label: '条码类型',
            prop: 'objectType',
            search: true,
            type: 'select',
            dicData: [
              {
                label: '序列号',
                value: 'PRODUCT'
              },
              {
                label: '载具',
                value: 'CARRIER'
              },
              {
                label: '包装条码',
                value: 'PACKING'
              }
            ],
            control: (val, form) => {
              switch (val) {
                case 'PRODUCT':
                  return {
                    objectSn: {
                      label: '序列号'
                    }
                  };
                case 'CARRIER':
                  return {
                    objectSn: {
                      label: '载具'
                    }
                  };
                case 'PACKING':
                  return {
                    objectSn: {
                      label: '包装条码'
                    }
                  };
                default:
                  break;
              }
            }
          },
          {
            label: '序列号',
            prop: 'objectSn',
            search: true,
            searchSpan: 8,
            rules: [
              {
                required: true,
                message: '请输入内容',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '报废对象',
            prop: 'partType',
            type: 'select',
            dicData: [
              {
                label: '原材料',
                value: 'MATERIAL'
              },
              {
                label: '在制品',
                value: 'PRODUCT'
              },
              {
                label: '在制品',
                value: 'SEMIFINISHED'
              }
            ]
          },
          {
            label: '报废类型',
            prop: 'scrapType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=scrapType',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '产品编码',
            prop: 'partNo'
          },
          {
            label: '产品名称',
            prop: 'partName'
          },
          {
            label: '产品型号',
            prop: 'partModel'
          }
        ]
      },
      data: [],

      printLabelModal: false,
      dialogTitle: '详情',
      // 报废详情
      scopeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '150',
        column: []
      },
      inventoryColumn: [
        {
          label: '条码类型',
          prop: 'objectType',
          search: true,
          type: 'select',
          disabled: true,
          dicData: [
            {
              label: '序列号',
              value: 'PRODUCT'
            },
            {
              label: '序列号',
              value: 'CARRIER'
            },
            {
              label: '包装条码',
              value: 'PACKING'
            }
          ]
        },
        {
          label: '报废类型',
          prop: 'scrapType',
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=scrapType',
          props: {
            label: 'dictValue',
            value: 'dictKey'
          },
          display: false
        },
        {
          label: '条码',
          prop: 'objectSn',
          disabled: true
        },
        {
          label: '条码数量',
          prop: 'quantity',
          disabled: true
        },
        {
          label: '不良来源',
          minWidth: 120,
          prop: 'registrySource',
          row: true,
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '自动',
              value: 'AUTO'
            },
            {
              label: '手动',
              value: 'MANUAL'
            }
          ]
        },
        {
          label: '料品编码',
          prop: 'partName',
          disabled: true
        },
        {
          label: '料品名称',
          prop: 'partNo',
          disabled: true
        },
        {
          label: '料品型号',
          prop: 'partModel',
          disabled: true
        },
        {
          label: '仓库',
          prop: 'inventoryName',
          disabled: true
        },
        {
          label: '储位',
          prop: 'areaName',
          disabled: true
        },
        {
          label: '报废原因',
          prop: 'scrapReason',
          disabled: true
        }
      ],
      // 产品报废
      productScopeColumn: [
        {
          label: '序列号',
          prop: 'objectSn',
          disabled: true
        },
        {
          label: '条码类型',
          prop: 'objectType',
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '序列号',
              value: 'PRODUCT'
            },
            {
              label: '载具',
              value: 'CARRIER'
            },
            {
              label: '包装条码',
              value: 'PACKING'
            }
          ]
        },
        {
          label: '产品数量',
          prop: 'quantity',
          disabled: true
        },
        {
          label: '不良来源',
          minWidth: 120,
          prop: 'registrySource',
          row: true,
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '自动',
              value: 'AUTO'
            },
            {
              label: '手动',
              value: 'MANUAL'
            }
          ]
        },
        {
          label: '当前所处工序',
          minWidth: 120,
          prop: 'currRouteName',
          disabled: true
        },
        {
          label: '报废类型',
          prop: 'scrapType',
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=scrapType',
          props: {
            label: 'dictValue',
            value: 'dictKey'
          },
          display: false
        },
        {
          label: '不良产生工序',
          minWidth: 120,
          prop: 'fromRouteName',
          disabled: true
        },
        {
          label: '不良代码',
          prop: 'failureCode',
          disabled: true
        },
        {
          label: '不良现象描述',
          minWidth: 120,
          prop: 'failureName',
          row: true,
          disabled: true
        },
        {
          label: '不良登记人员',
          minWidth: 120,
          prop: 'registryByName',
          disabled: true
        },
        {
          label: '不良登记时间',
          prop: 'registryDate',
          disabled: true,
          type: 'datetime'
        },
        {
          label: '报废原因',
          prop: 'scrapReason',
          disabled: true
        },
        {
          label: '工单号',
          prop: 'workOrderNo',
          disabled: true
        },
        {
          label: '车间',
          prop: 'workshopName',
          disabled: true
        },
        {
          label: '产线',
          prop: 'lineName',
          disabled: true
        },
        {
          label: '产品名称',
          prop: 'partName',
          disabled: true
        },
        {
          label: '产品编码',
          prop: 'partNo',
          disabled: true
        },
        {
          label: '产品型号',
          prop: 'partModel',
          disabled: true
        }
      ],
      // 原材料报废
      rowScopeColumn: [
        {
          label: '产品序列号/包装条码',
          prop: 'name',
          disabled: true
        },
        {
          label: '报废类型',
          prop: 'scrapType',
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=scrapType',
          props: {
            label: 'dictValue',
            value: 'dictKey'
          },
          disabled: true
        },
        {
          label: '产品编码',
          prop: 'partNo'
        },
        {
          label: '产品名称',
          prop: 'partName'
        },
        {
          label: '产品型号',
          prop: 'partModel'
        }
      ],
      // 维修报废
      repairScopeColumn: [
        {
          label: '序列号',
          prop: 'objectSn',
          disabled: true
        },
        {
          label: '条码类型',
          prop: 'objectType',
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '序列号',
              value: 'PRODUCT'
            },
            {
              label: '载具',
              value: 'CARRIER'
            },
            {
              label: '包装条码',
              value: 'PACKING'
            }
          ]
        },
        {
          label: '报废类型',
          prop: 'scrapType',
          type: 'select',
          dicUrl: '/api/blade-system/dict/dictionary?code=scrapType',
          props: {
            label: 'dictValue',
            value: 'dictKey'
          },
          display: false
        },
        {
          label: '产品数量',
          prop: 'quantity',
          disabled: true
        },
        {
          label: '不良来源',
          minWidth: 120,
          prop: 'registrySource',
          row: true,
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '自动',
              value: 'AUTO'
            },
            {
              label: '手动',
              value: 'MANUAL'
            }
          ]
        },
        {
          label: '当前所处工序',
          minWidth: 120,
          prop: 'currRouteName',
          disabled: true
        },
        {
          label: '不良产生工序',
          minWidth: 120,
          prop: 'routeName',
          disabled: true
        },
        {
          label: '不良代码',
          prop: 'failureCode',
          disabled: true
        },
        {
          label: '不良现象描述',
          minWidth: 120,
          prop: 'failureName',
          row: true,
          disabled: true
        },
        {
          label: '不良登记人员',
          minWidth: 120,
          prop: 'registryByName',
          disabled: true
        },
        {
          label: '不良登记时间',
          prop: 'registryDate',
          disabled: true,
          type: 'datetime'
        },
        {
          label: '不良原因大类',
          minWidth: 120,
          prop: 'mainCauseName',
          disabled: true
        },
        {
          label: '不良原因小类',
          minWidth: 120,
          prop: 'subCauseName',
          disabled: true
        },
        {
          label: '不良确认人员',
          minWidth: 120,
          prop: 'confirmByName',
          disabled: true
        },
        {
          label: '不良确认时间',
          minWidth: 120,
          prop: 'confirmTime',
          type: 'datetime',
          disabled: true
        },
        {
          label: '进维修时间',
          minWidth: 120,
          prop: 'repairInTime',
          type: 'datetime',
          disabled: true
        },
        {
          label: '维修执行人员',
          prop: 'repairByName',
          disabled: true
        },
        {
          label: '维修代码',
          prop: 'repairCode',
          disabled: true
        },
        {
          label: '维修完成时间',
          minWidth: 120,
          prop: 'registryDate',
          disabled: true
        },
        {
          label: '维修结果',
          prop: 'repairHandlingResult',
          disabled: true,
          type: 'select',
          dicData: [
            {
              label: '重新维修',
              value: 'REMRO'
            },
            {
              label: '维修报废',
              value: 'SCRAP'
            },
            {
              label: '维修报废',
              value: 'SUCCESS'
            }
          ]
        },
        {
          label: '报废原因',
          prop: 'scrapReason',
          disabled: true
        },
        {
          label: '工单号',
          prop: 'workOrderNo',
          disabled: true
        },
        {
          label: '车间',
          prop: 'workshopName',
          disabled: true
        },
        {
          label: '产线',
          prop: 'lineName',
          disabled: true
        },
        {
          label: '产品名称',
          prop: 'partName',
          disabled: true
        },
        {
          label: '产品编码',
          prop: 'partNo',
          disabled: true
        },
        {
          label: '产品型号',
          prop: 'partModel',
          disabled: true
        }
      ],
      scopeDetail: {}
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.sequencedefinition_add, false),
        viewBtn: this.vaildData(this.permission.scopeConfim_view, false),

        delBtn: this.vaildData(this.permission.sequencedefinition_delete, false),
        editBtn: this.vaildData(this.permission.sequencedefinition_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.scopeProdList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowDblclick(row) {
      console.log('ppps', row, this.scopeProdList);
      if (this.scopeProdList.length > 0) {
        let findIndex = this.scopeProdList.findIndex((item) => item.id === row.id);
        if (findIndex > -1) {
          this.scopeProdList.splice(findIndex, 1);
          row.isCheck = '';
        }
      }
    },
    // 拒收
    onRejection() {
      this.$confirm('确定将数据拒收吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return refuseScrap({ id: this.scopeDetail.id });
        })
        .then(() => {
          this.printLabelModal = false;
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    tableRowClassName({ row, rowIndex }) {
      let className = row.isCheck ? 'repair-select-row' : '';
      return className;
    },
    // 确认报废
    onScopeSure() {
      if (this.scopeProdList.length < 1) {
        this.$message.error('请确认已选中需报废的数据！');
        return;
      }
      this.$confirm('确定将选择数据报废?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          var arr = [];
          this.scopeProdList.forEach((item) => {
            const arrItem = {
              handleType: this._get(item, 'scrapType', ''),
              id: this._get(item, 'id', ''),
              productId: this._get(item, 'productId', ''),
              productSequenceNumber: this._get(item, 'productSequenceNumber', ''),
              partMasterId: this._get(item, 'partMasterId', ''),
              partNo: this._get(item, 'partNo', ''),
              registrySource: this._get(item, 'registrySource', ''),
              status: this._get(item, 'status', ''),
              quantity: '1'
            };
            arr.push(arrItem);
          });
          return confirmScrap(arr);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    async detailEvent(row) {
      this.newKey();
      this.printLabelModal = true;
      // 配置展示维修报废
      // this.scopeOption.column = this.repairScopeColumn
      if (row.scrapType === 'P-SCRAP') {
        this.$nextTick(() => {
          this.sequenceNumberTable = false;
        });
        this.scopeOption.column = this.productScopeColumn;
      } else if (row.scrapType === 'M-SCRAP') {
        this.$nextTick(() => {
          this.sequenceNumberTable = false;
        });
        this.scopeOption.column = this.repairScopeColumn;
      } else if (row.scrapType === 'W-SCRAP') {
        this.scopeOption.column = this.inventoryColumn;
        this.$nextTick(() => {
          this.sequenceNumberTable = true;
        });
        // let data = await getProductSequenceInfo({
        //   packId: row.objectId
        // });
        // this.sequenceData = data.data.data;
        // console.log(this.sequenceData, 'this.sequenceData');
      }

      // this.scopeOption.column = this.productScopeColumn
      getDetail(row.id).then((res) => {
        if (res.data.data) {
          this.scopeDetail = res.data.data;
          if (row.scrapType === 'W-SCRAP') {
            this.sequenceData = this.scopeDetail.productList;
          }
        }
      });
    },
    searchReset() {
      this.query = {};
    },
    searchChange(params, done) {
      this.data.forEach((item) => {
        if (item.objectSn === this.search.objectSn && item.objectType === this.search.objectType) {
          // this.$refs.crud.toggleRowSelection(item, true);
          this.scopeProdList.push(item);
        }
      });
      this.search.objectSn = '';
      console.log('params', params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      // this.scopeProdList = [];
      // this.$refs.crud.toggleSelection();
    },
    refreshChange() {},
    submitEvent() {
      submit(this.data).then((res) => {
        this.data = [];
        this.$message({
          type: 'success',
          message: '操作成功!'
        });
      });
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.statusStr = '3';
      getList(Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        // this.page.total = data.total;
        // [] || dataListTable
        this.data = data;
        this.loading = false;
        this.selectionClear();
      });
    },
    badCodeEntry(objectSn, objectType, type) {
      let data = this._cloneDeep(this.data);
      let items = this._remove(data, (item) => {
        return item.objectSn === objectSn && item.objectType === objectType;
      }).map((item) => {
        item.isCheck = type === 'input' ? true : false;
        // item.failureName = type === 'input' ? badCodeItem.name : '';
        return item;
      });
      this.data = type === 'input' ? items.concat(data) : data.concat(items);
      this.filtersFailureSequenceNumber();
    },
    filtersFailureSequenceNumber() {
      this.selectionList = this._filter(this.data, (item) => {
        return item.isCheck === true;
      });
    },
    submitSequenceNumber() {
      if (!this.search.objectType) {
        this.$message.warning('请选择条码类型');
        return false;
      }
      if (!this.search.objectSn) {
        this.$message.warning('请输入产品序列号');
        return false;
      }

      let params = {
        objectSn: this.search.objectSn,
        objectType: this.search.objectType
      };
      getList(params).then((res) => {
        this.data.forEach((item) => {
          if (item.objectSn === this.search.objectSn && item.objectType === this.search.objectType) {
            let find = this.scopeProdList.find((list) => list.objectSn == this.search.objectSn && item.objectType == this.search.objectType);
            if (!find) {
              this.scopeProdList.push(item);
            }
          }
        });
        this.badCodeEntry(this.search.objectSn, this.search.objectType, 'input');
        this.search.objectSn = '';
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}
::v-deep .el-table .repair-select-row {
  //   background-color: rgba(231, 67, 67, 1) !important;
  background-color: #caf982 !important;
  //   color: white;
}
::v-deep .el-dialog__body {
  padding: 15px 24px;
  .avue-crud__menu {
    display: none;
  }
}
</style>
